package project.pianpian.utils;

import com.auth0.jwt.JWT;
import com.auth0.jwt.algorithms.Algorithm;
import com.auth0.jwt.interfaces.DecodedJWT;
import com.auth0.jwt.interfaces.JWTVerifier;

import java.util.Date;
import java.util.HashMap;
import java.util.Map;

public class Token {

    //设置过期时间,7天过期1000*60*60*24*7
    private static final long EXPIRE_DATE=1000*60*60*24*7;
    //token秘钥
    private static final String TOKEN_SECRET = "ZCEQIUBFKSJBFJH2020BQWE";


    public static String create(int id,String password){

        String token = "";
        try {
            //过期时间
            Date date = new Date(System.currentTimeMillis()+EXPIRE_DATE);
            //秘钥及加密算法
            Algorithm algorithm = Algorithm.HMAC256(TOKEN_SECRET);
            //设置头部信息
            Map<String,Object> header = new HashMap<>();
            header.put("type","JWT");
            header.put("algorithm","HS256");
            //携带username，password信息，生成签名
            token = JWT.create()
                    .withHeader(header)
                    .withClaim("id",id)
                    .withClaim("password",password).withExpiresAt(date)
                    .sign(algorithm);
        }catch (Exception e){
            e.printStackTrace();
            return null;
        }
        return token;
    }
    //解码token
    public static Map verify(String token){
        /**
         * @desc   验证token，通过返回true
         * @create 2019/1/18/018 9:39
         * @params [token]需要校验的串
         **/
        try {
            Algorithm algorithm = Algorithm.HMAC256(TOKEN_SECRET);
            JWTVerifier verifier = JWT.require(algorithm).build();
            DecodedJWT jwt = verifier.verify(token);
            Map map=new HashMap();
            map.put("id",jwt.getClaim("id").asInt());
            map.put("password",jwt.getClaim("password").asString());
            map.put("deadline",jwt.getExpiresAt());
            return map;
        }catch (Exception e){
            e.printStackTrace();
            return null;
        }
    }
    public static void main(String[] args) {
        int id =2;
        String password = "123456";
        String token = create(id,password);
        System.out.println(token);
        Map b = verify(token);
        System.out.println(b);
        System.out.println(b.get("id")+" "+b.get("password"));
        System.out.println(b.get("deadline"));
    }
}
